package com.winning.pmph.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.winning.pmph.ctrl.YmerFileCtrl;
import com.winning.pmph.entity.*;
import com.winning.pmph.mapper.*;
import com.winning.pmph.utils.*;
import com.winning.pmph.vo.ExcelDb;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@Transactional
public class KnowledgeLibService extends ServiceImpl<KnowledgeLibMapper, KnowledgeLib> {
    @Resource
    private KnowledgeLibService knowledgeLibService;
    @Resource
    private KnowledgeLibFieldMapper knowledgeLibFieldMapper;
    @Resource
    private KnowledgeLibFieldService knowledgeLibFieldService;
    @Resource
    private WordsService wordsService;
    @Resource
    private TagService tagService;
    @Resource
    private RuleItemService ruleItemService;
    @Resource
    private TempKnowledgeService tempKnowledgeService;
    @Resource
    private ReleasedKnowledgeService releasedKnowledgeService;
    @Resource
    private KnowledgeAuditPackService knowledgeAuditPackService;
    @Resource
    private TempKnowledgeFieldService tempKnowledgeFieldService;
    @Resource
    private ReleasedKnowledgeFieldService releasedKnowledgeFieldService;
    @Resource
    private KnowledgeHistoryService knowledgeHistoryService;
    @Resource
    private KnowledgeFieldHistoryService knowledgeFieldHistoryService;
    @Resource
    private KnowledgePackMapper knowledgePackMapper;
    @Resource
    private KnowledgeSyncStatusService knowledgeSyncStatusService;
    @Resource
    private HistoryMapper historyMapper;
    @Resource
    private LastEditedFieldMapper lastEditedFieldMapper;
    @Resource
    private TaskService taskService;
    @Resource
    private TaskItemService taskItemService;
    @Resource
    private PlatformService platformService;
    @Resource
    private PlatformKnowledgeLibMapper platformKnowledgeLibMapper;
    @Resource
    private PlatformKnowledgeLibService platformKnowledgeLibService;
    @Resource
    private RocketMQProducerService rocketMQProducerService;
    @Resource
    private ActivityItemService activityItemService;
    @Resource
    private SpecialtyKnowledgeLibService specialtyKnowledgeLibService;
    @Resource
    private DataPermissionService dataPermissionService;
//    @Resource
//    private FileLibService fileLibService;
//    @Resource
//    private FileLibRefService fileLibRefService;

    public List<KnowledgeLibField> getKnowledgeLibFieldList(String knowledgeLibId) {
        return knowledgeLibFieldService.lambdaQuery()
                .eq(KnowledgeLibField::getKnowledgeLibId, knowledgeLibId)
                .orderByAsc(KnowledgeLibField::getIndex).list();
    }

    /**
     * @param id
     */

    public int deleteStringByFieldId(String id, String text) {
        if ("".equals(text)) {
            List<TempKnowledge> tempKnowledges = tempKnowledgeService.lambdaQuery().eq(TempKnowledge::getKnowledgeLibId, id).list();
            List<ReleasedKnowledge> releasedKnowledges = releasedKnowledgeService.lambdaQuery().eq(ReleasedKnowledge::getKnowledgeLibId, id).list();
            if (tempKnowledges.size() > 0 || releasedKnowledges.size() > 0) {
                return 0;
            } else {
                knowledgeLibService.getBaseMapper().deleteById(id);
                knowledgeLibFieldMapper.delete(new LambdaUpdateWrapper<KnowledgeLibField>().eq(KnowledgeLibField::getKnowledgeLibId, id));
                // 删除知识库时,如果有对应的专科库,则删除关联关系
                List<SpecialtyKnowledgeLib> list = specialtyKnowledgeLibService.lambdaQuery().like(SpecialtyKnowledgeLib::getKnowledgeLibIdList, id).list();
                list.forEach(item -> {
                    item.getKnowledgeLibIdList().remove(id);
                });
                specialtyKnowledgeLibService.updateBatchById(list);
            }
        } else {
            knowledgeLibFieldMapper.delete(new LambdaUpdateWrapper<KnowledgeLibField>().eq(KnowledgeLibField::getKnowledgeLibId, id));
        }


        return 1;
    }

    @SuppressWarnings("unchecked")
    public List<ReleasedKnowledge> queryReleasedKnowledgeList(int currentPage, int pageNum, String status, String updateTime, String classify, String platform, String version, String editor, String auditor, String name, String id, String queryStatus, String drugInfoLibCompany, Integer isCompose) {
        List<ReleasedKnowledge> releasedKnowledge = null;
        if ("published".equals(status)) {
            String sql = "select *," +
                    "case knowledge_lib_id when '" + Const.DRUG_INFO_LIB_ID + "' then (select property from released_knowledge_field where released_knowledge.id = released_knowledge_field.knowledge_id and knowledge_lib_field_id = '" + Const.DRUG_INFO_LIB_COMPANY_ID + "') else '' end as 'drugInfoLibCompany'," +
                    "case knowledge_lib_id when '" + Const.DRUG_INFO_LIB_ID + "' then (select property from released_knowledge_field where released_knowledge.id = released_knowledge_field.knowledge_id and knowledge_lib_field_id = '" + Const.DRUG_INFO_LIB_SOURCE_ID + "') else '' end as 'drugInfoLibSource' " +
                    " from released_knowledge where deleted = 0 and knowledge_lib_id = " + "'" + id + "'";
            sql = getReleaseSearch(updateTime, classify, platform, version, editor, auditor, name, sql, drugInfoLibCompany, isCompose);
            if (queryStatus == null) {
                sql += " order by updated_time desc limit " + currentPage * pageNum + ", " + pageNum;
            } else {
                sql += " order by updated_time desc";
            }

            releasedKnowledge = releasedKnowledgeService.getBaseMapper().executeMultiSelect(sql);
            if (releasedKnowledge.size() > 0) {
                String knowledgeLibId = releasedKnowledge.get(0).getKnowledgeLibId();
                KnowledgeLib knowledgeLib = knowledgeLibService.getBaseMapper().selectById(knowledgeLibId);
                return releasedKnowledge.stream().peek(knowledge -> knowledge.setKnowledgeLibName(knowledgeLib.getName())).collect(Collectors.toList());
            }
        }
        return releasedKnowledge;
    }

    public String getReleaseSearch(String updateTime, String classify, String platform, String version, String editor, String auditor, String name, String sql, String drugInfoLibCompany, Integer isCompose) {
        if (StringUtils.isNotBlank(updateTime)) {
            String startTime = (updateTime.split(",")[0].trim());
            String endTime = (updateTime.split(",")[1].trim());
            sql += " and updated_time >= '" + startTime + "' and updated_time <= '" + endTime + "' ";
        }
        if (StringUtils.isNotBlank(classify) && !"\"\"".equals(classify) && !"[]".equals(classify)) {
            sql += "and id in(select KNOWLEDGE_ID from released_knowledge_field  where property ='" + classify + "')";
        }
        if (CollectionUtils.isNotEmpty(JSON.parseArray(platform))) {
            sql += " and id in(select KNOWLEDGE_ID from released_knowledge_field where kind = " + KnowledgeLibField.FIELD_KIND_ASSOCIATE_PLATFORM + " and JSON_CONTAINS(property, '" + platform + "'))";
        }
        if (StringUtils.isNotBlank(version)) {
            sql += " and version = '" + version + "'";
        }
        if (StringUtils.isNotBlank(editor)) {
            sql += " and id in (select knowledge_id from task_item where editor = '" + editor + "')";
        }
        if (StringUtils.isNotBlank(auditor)) {
            sql += " and id in (select knowledge_id from task_item where first_auditor = '" + auditor + "' or second_auditor = '" + auditor + "' or third_auditor = '" + auditor + "')";
        }
        if (StringUtils.isNotBlank(name)) {
            sql += " and name like '%" + name + "%'";
        }
        if (StringUtils.isNotBlank(drugInfoLibCompany)) {
            sql += " and id in (select knowledge_id from released_knowledge_field where knowledge_lib_field_id = '" + Const.DRUG_INFO_LIB_COMPANY_ID + "' and property like '%" + drugInfoLibCompany + "%')";
        }
        if (Objects.nonNull(isCompose)) {
            sql += " and is_compose = " + isCompose;
        }
        return sql;
    }

    public int getReleasedKnowledgeTotalNum(String updateTime, String classify, String platform, String version, String editor, String auditor, String name, String id, String drugInfoLibCompany, Integer isCompose) {
        String sql = "select count(*) from released_knowledge where deleted=0 and knowledge_lib_id =" + "'" + id + "'";
        sql = getReleaseSearch(updateTime, classify, platform, version, editor, auditor, name, sql, drugInfoLibCompany, isCompose);
        return releasedKnowledgeService.getBaseMapper().selectInt(sql);
    }

    private String getTempSearch(String updateTime, String classify, String platform, String version, String editor, String auditor, String name, String sql, String drugInfoLibCompany, Integer isCompose) {
        if (StringUtils.isNotBlank(updateTime)) {
            String startTime = (updateTime.split(",")[0].trim());
            String endTime = (updateTime.split(",")[1].trim());
            sql += " and updated_time >= '" + startTime + "' and updated_time <= '" + endTime + "'";
        }
        if (CollectionUtils.isNotEmpty(JSON.parseArray(classify))) {
            sql += " and id in(select KNOWLEDGE_ID from temp_knowledge_field  where property ='" + classify + "')";
        }
        if (CollectionUtils.isNotEmpty(JSON.parseArray(platform))) {
            sql += " and id in(select KNOWLEDGE_ID from temp_knowledge_field where kind = " + KnowledgeLibField.FIELD_KIND_ASSOCIATE_PLATFORM + " and JSON_CONTAINS(property, '" + platform + "'))";
        }
        if (StringUtils.isNotBlank(version)) {
            sql += " and version = '" + version + "'";
        }
        if (StringUtils.isNotBlank(editor)) {
            sql += " and id in (select knowledge_id from task_item where editor = '" + editor + "')";
        }
        if (StringUtils.isNotBlank(auditor)) {
            sql += " and id in (select knowledge_id from task_item where first_auditor = '" + auditor + "' or second_auditor = '" + auditor + "' or third_auditor = '" + auditor + "')";
        }
        if (StringUtils.isNotBlank(name)) {
            sql += " and name like '%" + name + "%'";
        }
        if (StringUtils.isNotBlank(drugInfoLibCompany)) {
            sql += " and id in (select knowledge_id from temp_knowledge_field where knowledge_lib_field_id = '" + Const.DRUG_INFO_LIB_COMPANY_ID + "' and property like '%" + drugInfoLibCompany + "%')";
        }
        if (Objects.nonNull(isCompose)) {
            sql += " and is_compose = " + isCompose;
        }
        return sql;
    }


    /**
     * 新增页面保存方法
     *
     * @param knowledgeLibName
     * @param data
     * @return
     */


    public KnowledgeLib save(String knowledgeLibName, String data, String id, String specialtyId) {
        //构建KnowledgeLib实体
        KnowledgeLib kLib;
        if ("".equals(id)) {
            KnowledgeLib knowledgeLib = new KnowledgeLib();
            knowledgeLib.setName(knowledgeLibName);
            knowledgeLibService.getBaseMapper().insert(knowledgeLib);
            kLib = knowledgeLib;
            // 如果从专科知识词条进入页面，新建的知识库属于该专科库
            if (StringUtils.isNotBlank(specialtyId)) {
                SpecialtyKnowledgeLib specialtyKnowledgeLib = specialtyKnowledgeLibService.getBaseMapper().selectById(specialtyId);
                specialtyKnowledgeLib.getKnowledgeLibIdList().add(knowledgeLib.getId());
                specialtyKnowledgeLibService.updateById(specialtyKnowledgeLib);
                kLib.setKnowledgeLibIdList(specialtyKnowledgeLib.getKnowledgeLibIdList());
            }
        } else {
            String sql = "update knowledge_lib set name='" + knowledgeLibName + "' where id='" + id + "'";
            knowledgeLibService.getBaseMapper().executeUpdate(sql);
            knowledgeLibFieldMapper.deleteBeansByWherePart(" knowledge_lib_id ='" + id + "'");
            kLib = knowledgeLibService.getBaseMapper().selectById(id);
        }

        JSONArray objects = JSONArray.parseArray(data);
        for (int i = 0; i < objects.size(); i++) {
            JSONObject dataJson = objects.getJSONObject(i);
            //从dataJson里获取key对应的value,构建KnowledgeLibField实体
            KnowledgeLibField knowledgeLibField = new KnowledgeLibField();
            if (StringUtils.isNoneEmpty(dataJson.getString("id"))) {
                knowledgeLibField.setId(dataJson.getString("id"));
            }
            knowledgeLibField.setKnowledgeLibId(kLib.getId());
            knowledgeLibField.setKind(Integer.parseInt(dataJson.getString("kind")));
            knowledgeLibField.setName(dataJson.getString("name"));
            knowledgeLibField.setRequired(dataJson.getBoolean("required"));
            knowledgeLibField.setKindValue(dataJson.getString("kindValue"));
            knowledgeLibField.setIndex(Integer.parseInt(dataJson.getString("index")));
            knowledgeLibFieldMapper.saveBean(knowledgeLibField);
        }

        return kLib;
    }


    /**
     * 设置页面保存方法
     */

    public boolean editSave(String name, String data, String id) {
        // 查询原knowledgeLib信息;
        KnowledgeLib oriKnowledgeLib = knowledgeLibService.getBaseMapper().selectById(id);
        // 查询原knowledgeLibField集合信息
        List<TempKnowledge> tempKnowledge = tempKnowledgeService.lambdaQuery().eq(TempKnowledge::getKnowledgeLibId, id).list();
        List<ReleasedKnowledge> releasedKnowledge = releasedKnowledgeService.lambdaQuery()
                .eq(ReleasedKnowledge::getKnowledgeLibId, id)
                .eq(ReleasedKnowledge::getDeleted, ReleasedKnowledge.DELETED_NO).list();
        String sql = "select * from knowledge_lib_field where KNOWLEDGE_LIB_ID = '" + id + "' ORDER BY `index`";
        List<KnowledgeLibField> oriKnowledgeLibFieldArray = knowledgeLibFieldMapper.executeMultiSelect(sql);
        sql = "update knowledge_lib set updated_by = '" + PMPHAppUtil.getCurrentUserEnName() + "', updated_time = '" + LocalDateTimeUtil.getNowAsString() + "'";

        if (!Objects.equals(name, oriKnowledgeLib.getName())) {
            sql += ", name = '" + name + "'";
        }
        sql += " where id = '" + id + "'";
        knowledgeLibService.getBaseMapper().executeUpdate(sql);
        if (tempKnowledge.size() > 0 || releasedKnowledge.size() > 0) {
            // 页面上的知识库字段
            List<KnowledgeLibField> newList = getNewList(data, id);
            // 数据库里存储的知识库字段
            List<KnowledgeLibField> oldList = getOldList(oriKnowledgeLibFieldArray);
            List<KnowledgeLibField> addList = null;
            List<KnowledgeLibField> updateList = null;
            List<KnowledgeLibField> deleteList = null;
            //新增字段list
            addList = getAddList(newList, id);
            //修改字段的list
            updateList = getUpdataList(newList, oldList);
            //删除字段的list
            deleteList = getDeleteList(newList, oldList);
            save(addList, updateList, deleteList, tempKnowledge, releasedKnowledge, id);
        } else {
            save(name, data, id, null);
        }
        ExecutorServiceFactory.getInstance().submit(() -> syncKnowledgeLib(oriKnowledgeLib, oriKnowledgeLibFieldArray));
        return true;
    }

    private void save(List<KnowledgeLibField> addList, List<KnowledgeLibField> updateList, List<KnowledgeLibField> deleteList, List<TempKnowledge> tempKnowledgeArray, List<ReleasedKnowledge> releasedKnowledgeArray, String id) {
        String username = PMPHAppUtil.getCurrentUserEnName();
        List<String> deleteIdList = deleteList.stream().map(KnowledgeLibField::getId).collect(Collectors.toList());
        //删除list里的数据
        saveDeleteList(deleteIdList);
        // 新增字段操作
        saveAddList(addList, tempKnowledgeArray, releasedKnowledgeArray, username);
        //修改字段操作
        saveUpdateList(updateList, tempKnowledgeArray, releasedKnowledgeArray, id, username);
    }

    private void saveUpdateList(List<KnowledgeLibField> updateList, List<TempKnowledge> tempKnowledgeArray, List<ReleasedKnowledge> releasedKnowledgeArray, String id, String username) {
        List<TempKnowledge> TempList = new ArrayList<>();
        // 查询当前知识库下temp表知识的所有id
        for (TempKnowledge temp : tempKnowledgeArray) {
            temp.setId(temp.getId());
            TempList.add(temp);
        }
        String temId = TempList.stream().map(TempKnowledge::getId).collect(Collectors.joining("','", "('", "')"));
        //修改知识库字段操作
        for (KnowledgeLibField knowledgeLibField : updateList) {
            //改后的知识名称
            String displayName = knowledgeLibField.getName();
            int index = knowledgeLibField.getIndex();
            knowledgeLibField.setId(knowledgeLibField.getId());
            knowledgeLibField.setIndex(index);
            knowledgeLibField.setKnowledgeLibId(id);
            knowledgeLibField.setName(displayName);
            knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
            knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
            knowledgeLibField.setRequired(knowledgeLibField.getRequired());
            knowledgeLibField.setKind(knowledgeLibField.getKind());
            knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
            String knowledgeLibFieldSql = "update knowledge_lib_field set name = '" + displayName + "', `index` = " + index + ", updated_by = '" + PMPHAppUtil.getCurrentUserEnName() + "', updated_time = '" + LocalDateTimeUtil.getNowAsString() + "', required = " + knowledgeLibField.getRequired() + " where id = '" + knowledgeLibField.getId() + "'";
            knowledgeLibFieldMapper.executeUpdate(knowledgeLibFieldSql);

            // 修改TempKnowledgeLibField操作
            String tempFieldId = knowledgeLibField.getId();
            String sql = "update temp_knowledge_field set display_name = '" + displayName + "', name = '" + displayName + "', `index`= " + index + ", required = " + knowledgeLibField.getRequired() + ", updated_by = '" + PMPHAppUtil.getCurrentUserEnName() + "', updated_time = '" + LocalDateTimeUtil.getNowAsString() + "' where knowledge_id in " + temId + " and knowledge_lib_field_id = '" + tempFieldId + "' and display_name = name  ";
            tempKnowledgeFieldService.getBaseMapper().executeUpdate(sql);

            String tmpSql = "update temp_knowledge_field set name = '" + displayName + "', `index`= " + index + ", required = " + knowledgeLibField.getRequired() + ", updated_by = '" + PMPHAppUtil.getCurrentUserEnName() + "', updated_time = '" + LocalDateTimeUtil.getNowAsString() + "' where knowledge_id in " + temId + " and knowledge_lib_field_id = '" + tempFieldId + "' and (display_name != name or display_name is null) ";
            tempKnowledgeFieldService.getBaseMapper().executeUpdate(tmpSql);
        }
        List<ReleasedKnowledge> releaseList = new ArrayList<>();
        //查询当前知识库下release表知识的所有id
        for (ReleasedKnowledge released : releasedKnowledgeArray) {
            released.setId(released.getId());
            releaseList.add(released);
        }
        //获取到所有已发布知识id的字符串
        String releaseId = releaseList.stream().map(ReleasedKnowledge::getId).collect(Collectors.joining("','", "('", "')"));
        for (KnowledgeLibField knowledgeLibField : updateList) {
            String displayName = knowledgeLibField.getName();
            int index = knowledgeLibField.getIndex();
            String releaseFieldId = knowledgeLibField.getId();
            String sql = "update released_knowledge_field set display_name = '" + displayName + "', name = '" + displayName + "', `index` = " + index + ", required = " + knowledgeLibField.getRequired() + ", updated_by = '" + PMPHAppUtil.getCurrentUserEnName() + "', updated_time = '" + LocalDateTimeUtil.getNowAsString() + "' where knowledge_id in " + releaseId + " and knowledge_lib_field_id = '" + releaseFieldId + "' and display_name = name ";
            releasedKnowledgeFieldService.getBaseMapper().executeUpdate(sql);
            String releasedSql = "update released_knowledge_field set name = '" + displayName + "', `index` = " + index + ", required = " + knowledgeLibField.getRequired() + ", updated_by = '" + PMPHAppUtil.getCurrentUserEnName() + "', updated_time = '" + LocalDateTimeUtil.getNowAsString() + "' where knowledge_id in " + releaseId + " and knowledge_lib_field_id='" + releaseFieldId + "' and (display_name != name or display_name is null) ";
            releasedKnowledgeFieldService.getBaseMapper().executeUpdate(releasedSql);
        }
    }

    private void saveAddList(List<KnowledgeLibField> addList, List<TempKnowledge> tempKnowledgeArray, List<ReleasedKnowledge> releasedKnowledgeArray, String username) {
        //新增知识库字段操作
        for (KnowledgeLibField knowledgeLibField : addList) {
            knowledgeLibField.setName(knowledgeLibField.getName());
            knowledgeLibField.setKind(knowledgeLibField.getKind());
            knowledgeLibField.setKnowledgeLibId(knowledgeLibField.getKnowledgeLibId());
            knowledgeLibField.setRequired(knowledgeLibField.getRequired());
            knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
            knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
            knowledgeLibField.setIndex(knowledgeLibField.getIndex());
            knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
            knowledgeLibFieldMapper.saveBean(knowledgeLibField);
        }
        // 新增TempKnowledgeField操作
        for (TempKnowledge temp : tempKnowledgeArray) {
            for (KnowledgeLibField knowledgeLibField : addList) {
                TempKnowledgeField tempKnowledgeField = new TempKnowledgeField();
                tempKnowledgeField.setName(knowledgeLibField.getName());
                tempKnowledgeField.setKind(knowledgeLibField.getKind());
                tempKnowledgeField.setKnowledgeId(temp.getId());
                tempKnowledgeField.setDisplayName("");
                tempKnowledgeField.setKindValue(knowledgeLibField.getKindValue());
                tempKnowledgeField.setIndex(knowledgeLibField.getIndex());
                tempKnowledgeField.setKindValue(knowledgeLibField.getKindValue());
                tempKnowledgeField.setKnowledgeLibFieldId(knowledgeLibField.getId());
                tempKnowledgeField.setRequired(knowledgeLibField.getRequired());
                tempKnowledgeField.setKindValue(knowledgeLibField.getKindValue());
                if (knowledgeLibField.getKind() == 11) {
                    tempKnowledgeField.setProperty("{\"paths\":[],\"type\":\"\",\"title\":\"\"}");
                } else if (knowledgeLibField.getKind() == 2 || knowledgeLibField.getKind() == 12 || knowledgeLibField.getKind() == 8 || knowledgeLibField.getKind() == 9 || knowledgeLibField.getKind() == 7 || knowledgeLibField.getKind() == 10) {
                    tempKnowledgeField.setProperty("[]");
                } else if (knowledgeLibField.getKind() == 4) {
                    tempKnowledgeField.setProperty("{\"paths\": [],\"additional\": \"\",\"comment\": \"\",\"type\": \"\",\"classification\": \"\",\"title\": \"\"}");
                }
                tempKnowledgeFieldService.saveOrUpdate(tempKnowledgeField);
            }
        }
        // 新增ReleasedKnowledgeField操作
        for (ReleasedKnowledge release : releasedKnowledgeArray) {
            for (KnowledgeLibField knowledgeLibField : addList) {
                ReleasedKnowledgeField releaseKnowledgeField = new ReleasedKnowledgeField();
                releaseKnowledgeField.setKnowledgeId(release.getId());
                releaseKnowledgeField.setKind(knowledgeLibField.getKind());
                releaseKnowledgeField.setName(knowledgeLibField.getName());
                releaseKnowledgeField.setDisplayName("");
                releaseKnowledgeField.setKindValue(knowledgeLibField.getKindValue());
                releaseKnowledgeField.setIndex(knowledgeLibField.getIndex());
                releaseKnowledgeField.setKindValue(knowledgeLibField.getKindValue());
                releaseKnowledgeField.setKnowledgeLibFieldId(knowledgeLibField.getId());
                releaseKnowledgeField.setRequired(knowledgeLibField.getRequired());
                releaseKnowledgeField.setKindValue(knowledgeLibField.getKindValue());
                if (knowledgeLibField.getKind() == 11) {
                    releaseKnowledgeField.setProperty("{\"paths\":[],\"type\":\"\",\"title\":\"\"}");
                } else if (knowledgeLibField.getKind() == 2 || knowledgeLibField.getKind() == 12 || knowledgeLibField.getKind() == 8 || knowledgeLibField.getKind() == 9 || knowledgeLibField.getKind() == 7 || knowledgeLibField.getKind() == 10) {
                    releaseKnowledgeField.setProperty("[]");
                } else if (knowledgeLibField.getKind() == 4) {
                    releaseKnowledgeField.setProperty("{\"paths\": [],\"additional\": \"\",\"comment\": \"\",\"type\": \"\",\"classification\": \"\",\"title\": \"\"}");
                }
                releasedKnowledgeFieldService.saveOrUpdate(releaseKnowledgeField);
            }
        }
    }

    private void saveDeleteList(List<String> deleteIdList) {
        for (String knowledgeLibFieldId : deleteIdList) {
            releasedKnowledgeFieldService.remove(Wrappers.lambdaQuery(ReleasedKnowledgeField.class)
                    .eq(ReleasedKnowledgeField::getKnowledgeLibFieldId, knowledgeLibFieldId));
            tempKnowledgeFieldService.remove(Wrappers.lambdaQuery(TempKnowledgeField.class)
                    .eq(TempKnowledgeField::getKnowledgeLibFieldId, knowledgeLibFieldId));
            knowledgeLibFieldMapper.deleteById(knowledgeLibFieldId);
        }
    }


    private List<KnowledgeLibField> getDeleteList(List<KnowledgeLibField> newList, List<KnowledgeLibField> oldList) {
        Map<String, KnowledgeLibField> oldMap = new HashMap<>();
        for (KnowledgeLibField field : oldList) {
            oldMap.put(field.getId(), field);
        }
        for (KnowledgeLibField field : newList) {
            boolean containId = oldMap.containsKey(field.getId());
            if (containId && field.getId() != null) {
                oldMap.remove(field.getId());
            }
        }
        return new ArrayList<>(oldMap.values());
    }

    private List<KnowledgeLibField> getUpdataList(List<KnowledgeLibField> newList, List<KnowledgeLibField> oldList) {
        Map<String, KnowledgeLibField> oldMap = new HashMap<>();
        for (KnowledgeLibField field : oldList) {
            oldMap.put(field.getId(), field);
        }
        List<KnowledgeLibField> updateList = new ArrayList<>();
        for (KnowledgeLibField field : newList) {
            boolean containId = oldMap.containsKey(field.getId());
            KnowledgeLibField knowledgeLibField = oldMap.get(field.getId());
            if (containId) {
                if (field.getKind() != knowledgeLibField.getKind()
                        || !StringUtils.equals(field.getKindValue(), knowledgeLibField.getKindValue())
                        || !StringUtils.equals(knowledgeLibField.getKindValue(), field.getKindValue())) {
                    throw new RuntimeException("知识库下已有知识，不可以修改字段类型,关联分类,选项");
                }
                if (!knowledgeLibField.getName().equals(field.getName()) || knowledgeLibField.getIndex() != field.getIndex() || knowledgeLibField.getRequired() != field.getRequired()) {
                    field.setId(field.getId());
                    field.setName(field.getName());
                    field.setKindValue(field.getKindValue());
                    field.setKind(field.getKind());
                    field.setKindValue(field.getKindValue());
                    field.setKindValue(field.getKindValue());
                    field.setIndex(field.getIndex());
                    field.setKnowledgeLibId(field.getKnowledgeLibId());
                    field.setRequired(field.getRequired());
                    updateList.add(field);
                }
            }
        }
        return updateList;
    }

    private List<KnowledgeLibField> getAddList(List<KnowledgeLibField> newList, String id) {
        List<KnowledgeLibField> addList = new ArrayList<>();
        for (KnowledgeLibField knowledgeLibField : newList) {
            if (StringUtils.isBlank(knowledgeLibField.getId())) {
                knowledgeLibField.setName(knowledgeLibField.getName());
                knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
                knowledgeLibField.setKind(knowledgeLibField.getKind());
                knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
                knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
                knowledgeLibField.setIndex(knowledgeLibField.getIndex());
                knowledgeLibField.setKnowledgeLibId(id);
                knowledgeLibField.setRequired(knowledgeLibField.getRequired());
                addList.add(knowledgeLibField);
            }
        }
        return addList;
    }

    private List<KnowledgeLibField> getOldList(List<KnowledgeLibField> oriKnowledgeLibFieldArray) {
        List<KnowledgeLibField> oldList = new ArrayList<>();
        for (KnowledgeLibField knowledgeLibField : oriKnowledgeLibFieldArray) {
            knowledgeLibField.setId(knowledgeLibField.getId());
            knowledgeLibField.setName(knowledgeLibField.getName());
            knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
            knowledgeLibField.setKind(knowledgeLibField.getKind());
            knowledgeLibField.setKindValue(knowledgeLibField.getKindValue());
            knowledgeLibField.setRequired(knowledgeLibField.getRequired());
            knowledgeLibField.setIndex(knowledgeLibField.getIndex());
            knowledgeLibField.setKnowledgeLibId(knowledgeLibField.getKnowledgeLibId());
            oldList.add(knowledgeLibField);
        }
        return oldList;
    }

    private List<KnowledgeLibField> getNewList(String data, String id) {
        List<KnowledgeLibField> newList = new ArrayList<>();
        JSONArray objects = JSONArray.parseArray(data);
        for (int i = 0; i < objects.size(); i++) {
            JSONObject dataJson = objects.getJSONObject(i);
            KnowledgeLibField knowledgeLibField = new KnowledgeLibField();
            knowledgeLibField.setId(dataJson.getString("id"));
            knowledgeLibField.setKnowledgeLibId(dataJson.getString("knowledgeLibId"));
            knowledgeLibField.setKind(Integer.parseInt(dataJson.getString("kind")));
            knowledgeLibField.setName(dataJson.getString("name"));
            knowledgeLibField.setRequired(dataJson.getBoolean("required"));
            knowledgeLibField.setKindValue(dataJson.getString("kindValue"));
            knowledgeLibField.setIndex(Integer.parseInt(dataJson.getString("index")));
            newList.add(knowledgeLibField);
        }
        return newList;
    }

    private void syncKnowledgeLib(KnowledgeLib oriKnowledgeLib, List<KnowledgeLibField> oriKnowledgeLibFieldArray) {
        // 修改后的知识库;
        KnowledgeLib dbKnowledgeLib = knowledgeLibService.getBaseMapper().selectById(oriKnowledgeLib.getId());
        // 修改后的知识库字段集合;
        List<KnowledgeLibField> dbKnowledgeLibFieldArray = knowledgeLibFieldMapper.selectBeansByWherePart("knowledge_lib_id = '" + oriKnowledgeLib.getId() + "'");
        // 原字段id集合;
        Set<String> oriIdSet = oriKnowledgeLibFieldArray.stream().map(KnowledgeLibField::getId).collect(Collectors.toSet());
        // 新增的字段对应tag;
        List<String> tagIdList = dbKnowledgeLibFieldArray.stream()
                .filter(field -> !oriIdSet.contains(field.getId()))
                .filter(field -> StringUtils.isNotEmpty(field.getKindValue()))
                .map(KnowledgeLibField::getKindValue)
                .collect(Collectors.toList());
        // 知识库绑定的平台集合;
        List<PlatformKnowledgeLib> platformKnowledgeLibs = platformKnowledgeLibMapper.selectBeansByWherePart("knowledge_lib_id = '" + oriKnowledgeLib.getId() + "'");
        for (PlatformKnowledgeLib pkl : platformKnowledgeLibs) {
            // 先同步tag, 再同步knowledgeLib
            if (CollectionUtils.isNotEmpty(tagIdList)) {
                // 查询当前平台绑定其它知识库字段对应的tag集合;
                List<KnowledgeLibField> knowledgeLibFields = knowledgeLibFieldService.getBaseMapper().executeMultiSelect("SELECT DISTINCT KIND_VALUE FROM knowledge_lib_field " +
                        "WHERE KNOWLEDGE_LIB_ID IN ( " +
                        "SELECT KNOWLEDGE_LIB_ID FROM platform_knowledge_lib " +
                        " WHERE platform_id = '" + pkl.getPlatformId() + "' AND KNOWLEDGE_LIB_ID != '" + dbKnowledgeLib.getId() + "' ) " +
                        "and KIND_VALUE is not null");
                Set<String> otherTagIdSet = knowledgeLibFields.stream().map(KnowledgeLibField::getKindValue).filter(StringUtils::isNotEmpty).collect(Collectors.toSet());
                for (String tagId : tagIdList) {
                    if (!otherTagIdSet.contains(tagId)) {
                        tagService.syncSubTagByTopTagId(pkl.getPlatformId(), tagId);
                    }
                }
            }
            // 同步knowledgeLib;
            List<KnowledgeLibField> knowledgeLibFields = knowledgeLibFieldMapper.executeMultiSelect(
                    "select * from knowledge_lib_field where knowledge_lib_id = '" + dbKnowledgeLib.getId() + "' order by `index`");
            dbKnowledgeLib.setFieldList(knowledgeLibFields);
            rocketMQProducerService.sendKnowledgeLib(pkl.getPlatformId(), dbKnowledgeLib);
        }
    }

    /**
     * 查询同步页面所有数据
     *
     * @param currentPage
     * @param pageNum
     * @param name
     * @param platform
     * @param synStatus
     * @return
     */

    public List<ReleasedKnowledge> querySynList(int currentPage, int pageNum, String name, String platform, String synStatus, String updateTime, String bindingPlatform, String id, String drugInfoLibCompany, Integer isCompose) {
        String sql = "select released_knowledge.*, knowledge_sync_status.kind as syncStatus, knowledge_sync_status.operated_time as operatedTime";
        sql += " from released_knowledge left join knowledge_sync_status on released_knowledge.id = knowledge_sync_status.knowledge_id and platform_id = '" + bindingPlatform + "'";
        sql += getWherePart(name, platform, synStatus, updateTime, bindingPlatform, id, drugInfoLibCompany, isCompose);
        sql += " order by knowledge_sync_status.operated_time desc ,released_knowledge.id asc limit " + currentPage * pageNum + " , " + pageNum;
        List<ReleasedKnowledge> releasedKnowledgeList = releasedKnowledgeService.getBaseMapper().executeMultiSelect(sql);
        if (CollectionUtils.isNotEmpty(releasedKnowledgeList)) {
            // 已确认过,动态字段没有类型是关联平台的
            KnowledgeLibField knowledgeLibField = knowledgeLibFieldService.lambdaQuery().select(KnowledgeLibField::getId)
                    .eq(KnowledgeLibField::getKnowledgeLibId, id)
                    .eq(KnowledgeLibField::getKind, KnowledgeLibField.FIELD_KIND_ASSOCIATE_PLATFORM).one();
            if (Objects.nonNull(knowledgeLibField)) {
                // 关联应用平台
                releasedKnowledgeList.forEach(t -> {
                    ReleasedKnowledgeField releasedKnowledgeField = releasedKnowledgeFieldService.lambdaQuery()
                            .eq(ReleasedKnowledgeField::getKnowledgeLibFieldId, knowledgeLibField.getId())
                            .eq(ReleasedKnowledgeField::getKnowledgeId, t.getId()).one();
                    if (CollectionUtils.isNotEmpty(JSON.parseArray(releasedKnowledgeField.getProperty()))) {
                        // property 存储格式为json数组
                        List<Platform> platforms = platformService.listByIds(JSONArray.parseArray(releasedKnowledgeField.getProperty(), String.class));
                        t.setRuleName(platforms.stream().map(Platform::getName).collect(Collectors.joining(";")));
                    }
                });
            }
            if (Const.DRUG_INFO_LIB_ID.equals(id)) {
                releasedKnowledgeList.forEach(t -> {
                    t.setDrugInfoLibCompany(releasedKnowledgeFieldService.lambdaQuery()
                            .eq(ReleasedKnowledgeField::getKnowledgeLibFieldId, Const.DRUG_INFO_LIB_COMPANY_ID)
                            .eq(ReleasedKnowledgeField::getKnowledgeId, t.getId()).one().getProperty());

                    t.setDrugInfoLibSource(releasedKnowledgeFieldService.lambdaQuery()
                            .eq(ReleasedKnowledgeField::getKnowledgeLibFieldId, Const.DRUG_INFO_LIB_SOURCE_ID)
                            .eq(ReleasedKnowledgeField::getKnowledgeId, t.getId()).one().getProperty());
                });
            }
        }
        return releasedKnowledgeList;
    }

    private String getWherePart(String name, String platform, String synStatus, String updateTime, String bindingPlatform, String id, String drugInfoLibCompany, Integer isCompose) {
        String whereCause = " where released_knowledge.deleted = " + ReleasedKnowledge.DELETED_NO + " and released_knowledge.knowledge_lib_id = '" + id + "'";
        if (StringUtils.isNotBlank(name)) {
            whereCause += " and released_knowledge.name like '%" + name + "%'";
        }
        if (StringUtils.isNotBlank(updateTime)) {
            String startTime = (updateTime.split(",")[0].trim());
            String endTime = (updateTime.split(",")[1].trim());
            whereCause += " and updated_time >= '" + startTime + "' and updated_time <= '" + endTime + "'";
        }
        if (StringUtils.isNotBlank(drugInfoLibCompany)) {
            whereCause += " and released_knowledge.id in (select knowledge_id from released_knowledge_field where knowledge_lib_field_id = '" + Const.DRUG_INFO_LIB_COMPANY_ID + "' and property like '%" + drugInfoLibCompany + "%')";
        }
        if (StringUtils.isNotBlank(platform)) {
            whereCause += " and released_knowledge.id in(select KNOWLEDGE_ID from released_knowledge_field where kind = " + KnowledgeLibField.FIELD_KIND_ASSOCIATE_PLATFORM + " and JSON_CONTAINS(property, '\"" + platform + "\"'))";
        }
        whereCause += " and released_knowledge.knowledge_lib_id in (select knowledge_lib_id from platform_knowledge_lib where platform_id = '" + bindingPlatform + "' and system_type = 'knowledge')";
        if (StringUtils.isNotBlank(synStatus) && Integer.valueOf(synStatus) == KnowledgeSyncStatus.FAILED_KIND_WAITING) {
            whereCause += " and released_knowledge.id not in (select knowledge_id from knowledge_sync_status where platform_id = '" + bindingPlatform + "' and kind != " + KnowledgeSyncStatus.FAILED_KIND_WAITING + ")";
        }
        if (StringUtils.isNotBlank(synStatus) && Integer.valueOf(synStatus) != KnowledgeSyncStatus.FAILED_KIND_WAITING) {
            whereCause += " and released_knowledge.id in (select knowledge_id from knowledge_sync_status where platform_id = '" + bindingPlatform + "' and kind = " + synStatus + ")";
        }
        if (Objects.nonNull(isCompose)) {
            whereCause += " and released_knowledge.is_compose = " + isCompose;
        }
        return whereCause;
    }

    /**
     * 查询同步页面行数
     *
     * @param name
     * @param platform
     * @param synStatus
     * @return
     */

    public int getTotalSynNum(String name, String platform, String synStatus, String updateTime, String bindingPlatform, String id, String drugInfoLibCompany, Integer isCompose) {
        String sql = "select count(*) from released_knowledge ";
        sql += getWherePart(name, platform, synStatus, updateTime, bindingPlatform, id, drugInfoLibCompany, isCompose);
        return releasedKnowledgeService.getBaseMapper().selectInt(sql);
    }


    public void deleteTempAndReleaseById(String id, String status) {
        if ("published".equals(status)) {
            ReleasedKnowledge knowledge = releasedKnowledgeService.getById(id);
            knowledge.setVersion(knowledge.getVersion() + 1);
            // 修改知识
            LambdaUpdateWrapper<ReleasedKnowledge> releasedKnowledgeUpdateWrapper = Wrappers.lambdaUpdate();
            releasedKnowledgeUpdateWrapper.set(ReleasedKnowledge::getDeleted, ReleasedKnowledge.DELETED_YES);
            releasedKnowledgeUpdateWrapper.set(ReleasedKnowledge::getVersion, knowledge.getVersion());
            releasedKnowledgeUpdateWrapper.eq(ReleasedKnowledge::getId, knowledge.getId());
            releasedKnowledgeService.update(releasedKnowledgeUpdateWrapper);
            ReleasedKnowledge releasedKnowledge = releasedKnowledgeService.getById(id);
            // 记录知识版本
            knowledgeHistoryService.add(releasedKnowledge);
            //修改投稿详情
            LambdaUpdateWrapper<ActivityItem> activityItemLambdaUpdateWrapper = Wrappers.lambdaUpdate();
            activityItemLambdaUpdateWrapper.set(ActivityItem::getDeleted, ActivityItem.DELETED_YES);
            activityItemLambdaUpdateWrapper.eq(ActivityItem::getKnowledgeId, knowledge.getId());
            activityItemService.update(activityItemLambdaUpdateWrapper);

            Map<String, Object> knowledgeMap = updateBindingKnowledge(knowledge);
            List<ReleasedKnowledge> rList = (List<ReleasedKnowledge>) knowledgeMap.get("releasedKnowledgeList");
            rList.forEach(rKnowledge -> {
                try {
                    FieldCompareUtil.recordChangesInKnowledgeFields(History.OPERATE_CORRECT, rKnowledge);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                knowledgeHistoryService.add(rKnowledge);
                HistoryUtils.save(rKnowledge.getId(), rKnowledge.getName(), History.OPERATE_CORRECT, History.OPERATE_RESULT_SUCCESS);
            });
            HistoryUtils.save(id, knowledge.getName(), History.OPERATE_DELETE, History.OPERATE_RESULT_SUCCESS);

            if (StringUtils.equals(knowledge.getKnowledgeLibId(), Const.DRUG_INFO_LIB_ID)) {
                List<Words> words1 = wordsService.getBaseMapper().selectBeansByWherePart(" knowledge_id like '%" + id + "%'");
                if (CollectionUtils.isNotEmpty(words1)) {
                    wordsService.getBaseMapper().deleteBatchIds(words1.stream().map(Words::getId).collect(Collectors.toList()));
                    drug2Words(knowledge);
                }
            } else {
                wordsService.getBaseMapper().selectBeansByWherePart(" knowledge_id='" + id + "'");
            }

            // 同步逻辑删除子任务,如果该知识有修订的,不允许删除,所以不加status = 8 的判断
            LambdaUpdateWrapper<TaskItem> taskItemUpdateWrapper = Wrappers.lambdaUpdate();
            taskItemUpdateWrapper.set(TaskItem::getDeleted, TaskItem.DELETED);
            taskItemUpdateWrapper.eq(TaskItem::getKnowledgeId, id);
            taskItemService.update(taskItemUpdateWrapper);
            // 同步删除;
            knowledge.setSyncOperation(ReleasedKnowledge.SYNC_OPERATION_DELETE);
            sync(knowledge);
        }
    }

    private void drug2Words(ReleasedKnowledge knowledge) {
        String wordSql = "select knowledge_id, max(case name when '通用名称' then property end) as name,\n" +
                "                max(case name when '英文名称' then property end) as english_name,\n" +
                "                max(case name when '商品名/商标名' then property end) as synonym,\n" +
                "                max(case name when '其他名称' then property end) as synonymBak,\n" +
                "                max(case name when '原研药' then property end) as tag from released_knowledge_field where KNOWLEDGE_ID in (select id from released_knowledge where name='" + knowledge.getName() + "' and deleted=0 ) group by knowledge_id";
        List<Words> wordsArray = wordsService.getBaseMapper().executeMultiSelect(wordSql);
        Map<String, List<Words>> collect = wordsArray.stream().collect(Collectors.groupingBy(Words::getName));
        for (String name : collect.keySet()) {
            Words words = new Words();
            words.setName(name);
            List<Words> wordsList = collect.get(name);
            words.setEnglishName(wordsList.stream().map(Words::getEnglishName).distinct().filter(org.apache.commons.lang.StringUtils::isNotBlank).collect(Collectors.joining(";")));
            words.setSynonym(Stream.concat(wordsList.stream().map(Words::getSynonym), wordsList.stream().map(Words::getSynonymBak))
                    .distinct().filter(org.apache.commons.lang.StringUtils::isNotBlank).collect(Collectors.joining(";")));
            words.setTag(wordsList.stream().map(Words::getTag)
                    .filter(org.apache.commons.lang.StringUtils::isNotBlank)
                    .flatMap(tag -> JSON.parseArray(tag).stream())
                    .map(JSON::toJSONString).distinct().filter(innerTagArrayStr -> !JSON.parseArray(innerTagArrayStr).isEmpty())
                    .collect(Collectors.joining(",", "[", "]")));
            words.setKnowledgeId(wordsList.stream().map(Words::getKnowledgeId).distinct().collect(Collectors.joining(";")));
            words.setKnowledgeLibId(Const.DRUG_INFO_LIB_ID);
            words.setSourceType(Words.STATUS_KNOWLEDGE);
            words.setDeleted(Words.DELETED_NO);
            words.setStatus(Words.PASS_NO);
            words.setCreatedBy("自动导入");
            words.setUpdatedBy("自动导入");
            words.setUpdatedTime(LocalDateTimeUtil.getNowAsString());
            List<Words> dbWordsArray = wordsService.getBaseMapper().selectBeansByWherePart("knowledge_lib_id = '" + Const.DRUG_INFO_LIB_ID + "' and name = '" + name + "'");
            if (CollectionUtils.isNotEmpty(dbWordsArray)) {
                words.setId(dbWordsArray.get(0).getId());
                words.setUpdatedTime(LocalDateTimeUtil.getNowAsString());
            }
            wordsService.saveOrUpdate(words);
        }
    }

    private void sync(ReleasedKnowledge knowledge) {
        List<PlatformKnowledgeLib> platformKnowledgeLibs = platformKnowledgeLibMapper.selectBeansByWherePart("knowledge_lib_id = '" + knowledge.getKnowledgeLibId() + "'");
        for (PlatformKnowledgeLib platformKnowledgeLib : platformKnowledgeLibs) {
            System.out.println("sync: platform: " + platformKnowledgeLib.getPlatformName() + ", knowledge: " + knowledge.getName());
            rocketMQProducerService.sendKnowledge(platformKnowledgeLib.getPlatformId(), knowledge, PMPHAppUtil.getCurrentUserEnName());
        }
    }

    /**
     * 更新关联本知识的知识
     *
     * @param knowledge 要删除的知识
     * @return 关联知识Map
     */
    public Map<String, Object> updateBindingKnowledge(Knowledge knowledge) {
        // 组装查询参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", knowledge.getName());
        jsonObject.put("id", knowledge.getId());

        Map<String, Object> listMap = new HashMap<>(2);
        List<ReleasedKnowledge> releasedKnowledgeList = updateBindingReleasedKnowledge(jsonObject);
        List<TempKnowledge> tempKnowledgeList = updateBindingTempKnowledge(jsonObject);
        listMap.put("releasedKnowledgeList", releasedKnowledgeList);
        listMap.put("tempKnowledgeList", tempKnowledgeList);
        return listMap;
    }

    private List<TempKnowledge> updateBindingTempKnowledge(JSONObject jsonObject) {
        List<TempKnowledgeField> fieldList = tempKnowledgeFieldService.getBaseMapper().selectByProperty(jsonObject.toJSONString());
        fieldList.forEach(field -> {
            String property = field.getProperty();
            JSONArray array = JSONArray.parseArray(property);
            array.remove(jsonObject);
            field.setProperty(array.toJSONString());
        });
        return updateTempKnowledgeField(fieldList);
    }

    private List<TempKnowledge> updateTempKnowledgeField(List<TempKnowledgeField> fieldList) {
        List<TempKnowledge> knowledgeList = new ArrayList<>();
        fieldList.forEach(field -> {
            tempKnowledgeFieldService.saveOrUpdate(field);
            String knowledgeId = field.getKnowledgeId();
            TempKnowledge knowledge = tempKnowledgeService.getById(knowledgeId);
            knowledgeList.add(knowledge);
        });
        return knowledgeList;
    }

    /**
     * 更新知识字段
     *
     * @param jsonObject 字段更新信息
     * @return 返回更新了的知识
     */
    private List<ReleasedKnowledge> updateBindingReleasedKnowledge(JSONObject jsonObject) {
        // 查找所有的关联知识字段
        List<ReleasedKnowledgeField> fieldList = releasedKnowledgeFieldService.getBaseMapper().selectByProperty(jsonObject.toJSONString());
        fieldList.forEach(field -> {
            String property = field.getProperty();
            JSONArray array = JSONArray.parseArray(property);
            array.remove(jsonObject);
            field.setProperty(array.toJSONString());
        });
        return updateReleasedKnowledgeField(fieldList);
    }

    private List<ReleasedKnowledge> updateReleasedKnowledgeField(List<ReleasedKnowledgeField> fieldList) {
        List<ReleasedKnowledge> knowledgeList = new ArrayList<>();
        fieldList.forEach(field -> {
            releasedKnowledgeFieldService.saveOrUpdate(field);
            String knowledgeId = field.getKnowledgeId();
            ReleasedKnowledge knowledge = releasedKnowledgeService.getById(knowledgeId);
            List<KnowledgeField> allFieldList = Lists.newArrayList();
            releasedKnowledgeFieldService.getBaseMapper().executeMultiSelect("select * from released_knowledge_field where knowledge_id = '" + knowledgeId + "'").forEach(allFieldList::add);
            knowledge.setKnowledgeFieldList(allFieldList);
            int version = knowledge.getVersion();
            knowledge.setVersion(version + 1);
            releasedKnowledgeService.save(knowledge);
            knowledgeList.add(knowledge);
        });
        return knowledgeList;
    }

    public Page<KnowledgeLib> getKnowledgeLibPage(KnowledgeLib knowledgeLibParam) {
        Page<KnowledgeLib> knowledgeLibPage = new Page<>(knowledgeLibParam.getCurrentPage(), knowledgeLibParam.getPageSize());
        LambdaQueryWrapper<KnowledgeLib> queryWrapper = Wrappers.lambdaQuery(KnowledgeLib.class);
        // 权限过滤(查看权限)
        List<String> permissionKnowledgeLibIdList = dataPermissionService.getCrtUserKnowledgeLibPermission();
        List<String> editKnowledgeLibIdList = dataPermissionService.getCrtUserEditKnowledgeLibPermission();
        List<String> pushKnowledgeLibIdList = dataPermissionService.getCrtUserPushKnowledgeLibPermission();
        if (CollectionUtils.isNotEmpty(permissionKnowledgeLibIdList)) {
            queryWrapper.in(KnowledgeLib::getId, permissionKnowledgeLibIdList);
        }
        // 名称搜索;
        queryWrapper.like(StringUtils.isNotEmpty(knowledgeLibParam.getName()), KnowledgeLib::getName, knowledgeLibParam.getName());
        // specialtyId搜索;
        if (StringUtils.isNotEmpty(knowledgeLibParam.getSpecialtyId())) {
            SpecialtyKnowledgeLib specialtyKnowledgeLib = specialtyKnowledgeLibService.getById(knowledgeLibParam.getSpecialtyId());
            queryWrapper.in(KnowledgeLib::getId, specialtyKnowledgeLib.getKnowledgeLibIdList().toJavaList(String.class));
        }
        // bindingPlatform搜索;
        if (CollectionUtils.isNotEmpty(knowledgeLibParam.getPlatformIdArray())) {
            List<String> knowledgeLibIdList = platformKnowledgeLibService.lambdaQuery()
                    .select(PlatformKnowledgeLib::getKnowledgeLibId)
                    .in(PlatformKnowledgeLib::getPlatformId, knowledgeLibParam.getPlatformIdArray()).list()
                    .stream().map(PlatformKnowledgeLib::getKnowledgeLibId).distinct().collect(Collectors.toList());
            queryWrapper.in(KnowledgeLib::getId, knowledgeLibIdList);
        }
        knowledgeLibPage = page(knowledgeLibPage, queryWrapper);

        for (KnowledgeLib knowledgeLib : knowledgeLibPage.getRecords()) {
            // 标记当前知识库有多少待发布任务;
            List<Task> taskList = taskService.lambdaQuery().select(Task::getId)
                    .eq(Task::getKnowledgeLibId, knowledgeLib.getId())
                    .eq(Task::getStatus, Task.STATUS_STARTED).list();
            if (CollectionUtils.isNotEmpty(taskList)) {
                Integer count = taskItemService.lambdaQuery()
                        .eq(TaskItem::getStatus, TaskItem.STATUS_PASS)
                        .in(TaskItem::getTaskId, taskList.stream().map(Task::getId).collect(Collectors.toList())).count();
                knowledgeLib.setWaitToPublishTaskItemCount(count);
            }
            List<KnowledgeLibField> knowledgeLibFields = knowledgeLibFieldService.lambdaQuery()
                    .eq(KnowledgeLibField::getKnowledgeLibId, knowledgeLib.getId()).list();
            knowledgeLib.setFieldList(knowledgeLibFields);
            knowledgeLib.setIsToPlatform(false);
            for (KnowledgeLibField field : knowledgeLibFields) {
                // 查询是否关联平台
                if (field.getKind() == KnowledgeLibField.FIELD_KIND_ASSOCIATE_PLATFORM) {
                    knowledgeLib.setIsToPlatform(true);
                }
            }
            // 查询知识库绑定的平台
            List<PlatformKnowledgeLib> platformKnowledgeLibList = platformKnowledgeLibService.lambdaQuery().select(PlatformKnowledgeLib::getPlatformId)
                    .eq(PlatformKnowledgeLib::getKnowledgeLibId, knowledgeLib.getId()).list();
            if (CollectionUtils.isNotEmpty(platformKnowledgeLibList)) {
                List<Platform> platformList = platformService.lambdaQuery().
                        in(Platform::getId, platformKnowledgeLibList.stream().map(PlatformKnowledgeLib::getPlatformId).collect(Collectors.toList()))
                        .list();
                knowledgeLib.setPlatformList(platformList);
            }
            // 编辑, 推送权限;
            if (CollectionUtils.isNotEmpty(editKnowledgeLibIdList)) {
                knowledgeLib.setEditFlag(editKnowledgeLibIdList.contains(knowledgeLib.getId()));
            } else {
                knowledgeLib.setEditFlag(true);
            }
            if (CollectionUtils.isNotEmpty(pushKnowledgeLibIdList)) {
                knowledgeLib.setPushFlag(pushKnowledgeLibIdList.contains(knowledgeLib.getId()));
            } else {
                knowledgeLib.setPushFlag(true);
            }
        }
        return knowledgeLibPage;
    }

    public int tempKnowledge2ReleaseKnowledge(String id, String name) {
        if (hasUnConfirmedNameSuggestion(id)) {
            throw new RuntimeException("存在未确认的名称修改建议!");
        }
        ReleasedKnowledge release = releasedKnowledgeService.getById(id);
        if (release != null) {
            releasedKnowledgeService.removeById(id);
            releasedKnowledgeFieldService.remove(Wrappers.lambdaQuery(ReleasedKnowledgeField.class)
                    .eq(ReleasedKnowledgeField::getKnowledgeId, id));
        }
        saveTempAndRelease(id);
        HistoryUtils.save(id, name, History.OPERATE_RELEASE, History.OPERATE_RESULT_SUCCESS);
        return 1;
    }

    private boolean hasUnConfirmedNameSuggestion(String knowledgeId) {
        // 根据知识id 校验, 当前绑定子任务是否存在名称待确认;
        List<TaskItem> taskItemList = taskItemService.lambdaQuery()
                .eq(TaskItem::getKnowledgeId, knowledgeId)
                .eq(TaskItem::getStatus, TaskItem.STATUS_PASS).list();
        for (TaskItem taskItem : taskItemList) {
            if (taskItem.getNameSuggestion().hasUnconfirmedNameSuggestion()) {
                taskItem.setPress(true);
                taskItemService.updateById(taskItem);
                return true;
            }
        }
        return false;
    }

    /**
     * 发布——单个
     *
     * @param id knowledge id
     */
    private void saveTempAndRelease(String id) {
        ReleasedKnowledge release = releasedKnowledgeService.getById(id);
        if (release != null) {
            releasedKnowledgeService.removeById(id);
            releasedKnowledgeFieldService.remove(Wrappers.lambdaQuery(ReleasedKnowledgeField.class)
                    .eq(ReleasedKnowledgeField::getKnowledgeId, id));
        }
        // 取得tempKnowledge
        TempKnowledge tempKnowledge = tempKnowledgeService.getById(id);
        // 构建releasedKnowledge
        ReleasedKnowledge releasedKnowledge = JSON.parseObject(JSON.toJSONString(tempKnowledge), ReleasedKnowledge.class);
        releasedKnowledge.setSyncStatus(ReleasedKnowledge.SYNC_STATUS_WAITING);
        releasedKnowledge.setSyncOperation(ReleasedKnowledge.SYNC_OPERATION_NEW);
        releasedKnowledge.setVersion(releasedKnowledge.getVersion() + 1);
        releasedKnowledge.setCreatedBy(tempKnowledge.getCreatedBy());
        releasedKnowledge.setUpdatedBy(tempKnowledge.getUpdatedBy());
        releasedKnowledgeService.save(releasedKnowledge);
        releasedKnowledgeService.update(Wrappers.lambdaUpdate(ReleasedKnowledge.class)
                .set(ReleasedKnowledge::getCreatedBy, tempKnowledge.getCreatedBy())
                .set(ReleasedKnowledge::getUpdatedBy, tempKnowledge.getUpdatedBy())
                .eq(ReleasedKnowledge::getId, releasedKnowledge.getId()));

        // 取得tempKnowledgeField
        List<TempKnowledgeField> tempKnowledgeFields = tempKnowledgeFieldService.lambdaQuery().eq(TempKnowledgeField::getKnowledgeId, id).orderByAsc(TempKnowledgeField::getId).list();
        // 构建ReleaseKnowledgeField对象数组
        List<ReleasedKnowledgeField> releasedKnowledgeFieldList = new ArrayList<>();
        for (TempKnowledgeField tempKnowledgeField : tempKnowledgeFields) {
            ReleasedKnowledgeField releaseKnowledgeField = JSON.parseObject(JSON.toJSONString(tempKnowledgeField), ReleasedKnowledgeField.class);
            releaseKnowledgeField.setKnowledgeLibFieldId(tempKnowledgeField.getKnowledgeLibFieldId());
            releasedKnowledgeFieldList.add(releaseKnowledgeField);
        }

        tempKnowledgeService.removeById(id);
        tempKnowledgeFieldService.remove(Wrappers.lambdaQuery(TempKnowledgeField.class).eq(TempKnowledgeField::getKnowledgeId, id));

        // 存储ReleaseKnowledgeField, 并向record表添加数据;
        releasedKnowledgeFieldService.saveOrUpdateBatch(releasedKnowledgeFieldList);
//        // 维护静态资源
//        fileLibService.insertKnowledgeFileLib(releasedKnowledge, JSONArray.toJSONString(releasedKnowledgeFieldList));

        taskItemService.getBaseMapper().executeUpdate("update task_item set status = " + TaskItem.STATUS_RELEASED + " where knowledge_id = '" + id + "'");
        // 根据平台自动同步开关是否开启决定是否发送到消息队列
        List<KnowledgeField> knowledgeFieldList = Lists.newArrayList();
        releasedKnowledgeFieldList.forEach((knowledgeFieldList::add));
        releasedKnowledge.setKnowledgeFieldList(knowledgeFieldList);
        // 记录知识版本
        knowledgeHistoryService.add(releasedKnowledge);
        String sql = "knowledge_lib_id = '" + releasedKnowledge.getKnowledgeLibId() + "'";
        List<PlatformKnowledgeLib> platformKnowledgeLibs = platformKnowledgeLibMapper.selectBeansByWherePart(sql);

        releasedKnowledge.setKnowledgeLibName(knowledgeLibService.getBaseMapper().selectById(releasedKnowledge.getKnowledgeLibId()).getName());
        for (PlatformKnowledgeLib platformKnowledgeLib : platformKnowledgeLibs) {
            if (Objects.equals(true, platformKnowledgeLib.isAutosyncFlag())) {
                // 发送到消息队列
                rocketMQProducerService.sendKnowledge(platformKnowledgeLib.getPlatformId(), releasedKnowledge, PMPHAppUtil.getCurrentUserEnName());
            } else {
                // 记录知识的未同步状态
                KnowledgeSyncStatus knowledgeSyncStatus = new KnowledgeSyncStatus();
                knowledgeSyncStatus.setKnowledgeId(releasedKnowledge.getId());
                knowledgeSyncStatus.setKnowledgeLibId(releasedKnowledge.getKnowledgeLibId());
                knowledgeSyncStatus.setKnowledgeName(releasedKnowledge.getName());
                knowledgeSyncStatus.setKind(KnowledgeSyncStatus.FAILED_KIND_WAITING);
                knowledgeSyncStatus.setVersion(releasedKnowledge.getVersion());
                knowledgeSyncStatus.setPlatformId(platformKnowledgeLib.getPlatformId());
                knowledgeSyncStatus.setOperatedTime(LocalDateTimeUtil.getNowAsString());
                saveKnowledgeSyncStatus(knowledgeSyncStatus);
            }
        }
    }

    /**
     * 发布——批量, 返回因名称修改建议而发布失败的条数;
     */

    public int TempAll2Release(List<TempKnowledge> tempKnowledgeList) {
        System.out.println(System.currentTimeMillis() + "开始时间-----------------------");
        int nameSuggestionCount = 0;
        for (TempKnowledge tempKnowledge : tempKnowledgeList) {
            if (hasUnConfirmedNameSuggestion(tempKnowledge.getId())) {
                nameSuggestionCount++;
                continue;
            }
            ReleasedKnowledge releasedKnowledge = releasedKnowledgeService.getById(tempKnowledge.getId());
            if (releasedKnowledge != null) {
                releasedKnowledgeService.removeById(releasedKnowledge.getId());
                releasedKnowledgeFieldService.remove(Wrappers.lambdaQuery(ReleasedKnowledgeField.class)
                        .eq(ReleasedKnowledgeField::getKnowledgeId, releasedKnowledge.getId()));
            }
            saveTempAndRelease(tempKnowledge.getId());
            HistoryUtils.save(tempKnowledge.getId(), tempKnowledge.getName(), History.OPERATE_RELEASE, History.OPERATE_RESULT_SUCCESS);
        }
        System.out.println(System.currentTimeMillis() + "结束时间-----------------------");
        return nameSuggestionCount;
    }


    public boolean saveKnowledgeExport(String id, String knowledgeSelect, String nameSelection, String name,
                                       String cause, String type, boolean includeDynamicField) {
        JSONArray knowledgeSelects = JSONArray.parseArray(knowledgeSelect);
        KnowledgeAuditPack knowledgeAuditPack = buildKnowledgeAuditPack(id, knowledgeSelects, name, cause, nameSelection, includeDynamicField);
        knowledgeAuditPack.setType(Integer.parseInt(type));
        knowledgeAuditPack.setStatus(2);
        knowledgeAuditPack.setDownloadTotal(0);
        knowledgeAuditPackService.save(knowledgeAuditPack);
        buildKnowledgePack(knowledgeAuditPack, knowledgeSelects);
        return true;
    }

    /**
     * 查询当前知识库下deleted为1的数据
     *
     * @return
     */

    public IPage<ReleasedKnowledge> queryDelList(Page<ReleasedKnowledge> page, TempKnowledge tempKnowledge) {
        return releasedKnowledgeService.getBaseMapper().queryDelList(page, tempKnowledge);
    }

    public void deleteReleasedKnowledge(String ids) {
        releasedKnowledgeService.getBaseMapper().deleteBeansByWherePart(" id in " + ids);
        releasedKnowledgeFieldService.getBaseMapper().deleteBeansByWherePart(" knowledge_id in " + ids);
        // 删除版本表
        knowledgeHistoryService.getBaseMapper().deleteBeansByWherePart(" knowledge_id in " + ids);
        knowledgeFieldHistoryService.getBaseMapper().deleteBeansByWherePart(" knowledge_id in " + ids);
        // 删除日志表
        historyMapper.deleteBeansByWherePart(" knowledge_id in " + ids);
        lastEditedFieldMapper.deleteBeansByWherePart(" knowledge_id in " + ids);
        // 删除对应的子任务表
        taskItemService.getBaseMapper().deleteBeansByWherePart(" knowledge_id in " + ids);
        // 删除投稿详情表
        activityItemService.getBaseMapper().deleteBeansByWherePart("knowledge_id in " + ids);
       /* // 先删除静态资源引用表  清空暂时不考虑超1000张图片  删除知识时,存在这条知识的部分图片未被别的地方引用
        List<FileLibRef> fileLibRefList = fileLibRefService.lambdaQuery().list();
        // 待删除的资源引用表
        List<FileLibRef> deleteFileLibRefList = fileLibRefList.stream().filter(item ->
                Arrays.asList(StringUtils.substring(ids, 1, ids.length() - 1).replace("'", "").split(","))
                        .contains(item.getKnowledgeId()))
                .collect(Collectors.toList());
        // 现在表中存在的数据
        fileLibRefList.removeAll(deleteFileLibRefList);
        // 删除静态资源引用表
        deleteFileLibRefList.add(new FileLibRef());
        fileLibRefService.removeByIds(deleteFileLibRefList.stream().map(FileLibRef::getId).collect(Collectors.toList()));
        // 待删除的静态资源表
        List<String> deleteFileLibIdList = deleteFileLibRefList.stream().filter(item -> !fileLibRefList.stream().map(FileLibRef::getFileLibId).collect(Collectors.toList())
                .contains(item.getFileLibId())).map(FileLibRef::getFileLibId).collect(Collectors.toList());
        // 删除静态资源表
        deleteFileLibIdList.add("");
        fileLibService.removeByIds(deleteFileLibIdList);*/
    }


    public void recoverReleasedKnowledge(String ids) {
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            // Update released knowledge deleted status
            ReleasedKnowledge knowledge = releasedKnowledgeService.getById(id);
            knowledge.setDeleted(ReleasedKnowledge.DELETED_NO);
            knowledge.setVersion(knowledge.getVersion() + 1);
            releasedKnowledgeService.updateById(knowledge);
            //修改投稿详情
            LambdaUpdateWrapper<ActivityItem> activityItemLambdaUpdateWrapper = Wrappers.lambdaUpdate();
            activityItemLambdaUpdateWrapper.set(ActivityItem::getDeleted, ActivityItem.DELETED_NO);
            activityItemLambdaUpdateWrapper.eq(ActivityItem::getKnowledgeId, knowledge.getId());
            activityItemService.update(activityItemLambdaUpdateWrapper);

            // 恢复子任务
            taskItemService.getBaseMapper().executeUpdate("update task_item set deleted = " + TaskItem.NO_DELETED + ", updated_time='" + LocalDateTimeUtil.getNowAsString() + "' where knowledge_id = '" + id + "'");
            //修改同步状态
            knowledgeSyncStatusService.getBaseMapper().executeUpdate("update knowledge_sync_status set kind = " + KnowledgeSyncStatus.FAILED_KIND_WAITING + " where knowledge_id = '" + id + "'");

            // Update knowledge_history deleted status
            String historySql = "update knowledge_history set deleted = 0 , updated_time='" + LocalDateTimeUtil.getNowAsString() + "' where knowledge_id = '" + id + "'";
            knowledgeHistoryService.getBaseMapper().executeUpdate(historySql);
            knowledgeHistoryService.add(knowledge);
            // Record operation history
            HistoryUtils.save(id, knowledge.getName(), History.OPERATE_RECOVER, History.OPERATE_RESULT_SUCCESS);
            knowledge.setSyncOperation(ReleasedKnowledge.SYNC_OPERATION_NEW);
            List<PlatformKnowledgeLib> platformKnowledgeLibs = platformKnowledgeLibMapper.selectBeansByWherePart("knowledge_lib_id = '" + knowledge.getKnowledgeLibId() + "'");
            for (PlatformKnowledgeLib platformKnowledgeLib : platformKnowledgeLibs) {
                if (platformKnowledgeLib.isAutosyncFlag()) {
                    rocketMQProducerService.sendKnowledge(platformKnowledgeLib.getPlatformId(), knowledge, PMPHAppUtil.getCurrentUserEnName());
                }
            }
        }
    }

    /**
     * 构建导出知识实体
     *
     * @param id
     * @param
     * @param name
     * @param cause
     * @return
     */
    private KnowledgeAuditPack buildKnowledgeAuditPack(String id, JSONArray knowledgeSelects, String name, String cause,
                                                       String nameSelection, boolean includeDynamicField) {
        KnowledgeAuditPack knowledgeAuditPack = new KnowledgeAuditPack();
        String excludeFieldNames = calculateExcludeFieldNames(id, nameSelection);
        if (includeDynamicField) {
            knowledgeAuditPack.setIncludeDynamicField(KnowledgeAuditPack.INCLUDE_DYNAMIC_FIELD);
        } else {
            knowledgeAuditPack.setIncludeDynamicField(KnowledgeAuditPack.NOT_INCLUDE_DYNAMIC_FIELD);
        }
        knowledgeAuditPack.setExclude(excludeFieldNames);
        knowledgeAuditPack.setName(name);
        knowledgeAuditPack.setType(1);
        knowledgeAuditPack.setKnowledgeLibId(id);
        knowledgeAuditPack.setCause(cause);
        knowledgeAuditPack.setKnowledgeTotal(knowledgeSelects.size());
        return knowledgeAuditPack;
    }

    private String calculateExcludeFieldNames(String id, String nameSelection) {
        JSONArray jsonArray = JSON.parseArray(nameSelection);
        List<String> includeFieldNames = new ArrayList<>();
        for (Object object : jsonArray) {
            String fieldName = (String) object;
            includeFieldNames.add(fieldName);
        }
        List<KnowledgeLibField> knowledgeLibFields = knowledgeLibFieldMapper.selectBeansByWherePart("knowledge_lib_id = '" + id + "'");
        StringBuilder stringBuilder = new StringBuilder();
        for (KnowledgeLibField field : knowledgeLibFields) {
            String fieldName = field.getName();
            if (includeFieldNames.contains(fieldName)) {
                continue;
            }
            stringBuilder.append(fieldName).append(",");
        }
        return StringUtils.removeEnd(stringBuilder.toString(), ",");
    }

    /**
     * 构建
     *
     * @param kAuditPack
     * @param knowledgeSelects
     */
    private void buildKnowledgePack(KnowledgeAuditPack kAuditPack, JSONArray knowledgeSelects) {
        for (int i = 0; i < knowledgeSelects.size(); i++) {
            JSONObject dataJson = knowledgeSelects.getJSONObject(i);
            String knowledgeId = dataJson.getString("id");
            String knowledgeLibId = dataJson.getString("knowledgeLibId");
            String knowledgeName = dataJson.getString("name");
            KnowledgePack knowledgePack = new KnowledgePack();
            knowledgePack.setKnowledgeId(knowledgeId);
            knowledgePack.setKnowledgeLibId(knowledgeLibId);
            knowledgePack.setKnowledgeName(knowledgeName);
            knowledgePack.setKnowledgeAuditPackId(kAuditPack.getId());
            knowledgePackMapper.saveBean(knowledgePack);
        }
    }


    public IPage<KnowledgeAuditPack> queryExportApplyList(Page<KnowledgeAuditPack> page, KnowledgeAuditPack knowledgeAuditPack) {
        return knowledgeAuditPackService.getBaseMapper().queryExportApplyList(page, knowledgeAuditPack);
    }

    public boolean deleteExportApplyById(String auditPackId) {
        boolean isSuccess = true;
        try {
            // 删除主表
            knowledgeAuditPackService.removeById(auditPackId);
            knowledgePackMapper.delete(Wrappers.lambdaQuery(KnowledgePack.class).eq(KnowledgePack::getKnowledgeAuditPackId, auditPackId));
        } catch (Exception e) {
            isSuccess = false;
        }
        return isSuccess;
    }


    public OutputStream downloadExportApplyExcel(KnowledgeAuditPack knowledgeAuditPack, OutputStream outputStream) throws Exception {
        List<ReleasedKnowledgeField> list = getList(knowledgeAuditPack);
        // 单选或者多选
        Map<String, Map<String, String>> map = Maps.newConcurrentMap();
        List<RuleItem> ruleItemList = ruleItemService.list();
        Map<String, List<RuleItem>> ruleMap = ruleItemList.stream().collect(Collectors.groupingBy(RuleItem::getRuleId));
        Map<String, String> itemMap = null;
        for (Map.Entry<String, List<RuleItem>> m : ruleMap.entrySet()) {
            itemMap = Maps.newConcurrentMap();
            for (RuleItem ruleItem : m.getValue()) {
                itemMap.put(ruleItem.getId(), ruleItem.getName());
            }
            map.put(m.getKey(), itemMap);
        }
        // 打包excel
        createExcel(list, knowledgeAuditPack, outputStream, map);
        // 更新修改次数
        updateDownloadNum(knowledgeAuditPack);
        return outputStream;
    }


    public String downloadExportApplyXml(KnowledgeAuditPack knowledgeAuditPack) throws Exception {
        List<ReleasedKnowledgeField> list = getList(knowledgeAuditPack);
        // 单选或者多选
        Map<String, Map<String, String>> map = Maps.newConcurrentMap();
        List<RuleItem> ruleItemList = ruleItemService.list();
        Map<String, List<RuleItem>> ruleMap = ruleItemList.stream().collect(Collectors.groupingBy(RuleItem::getRuleId));
        Map<String, String> itemMap = null;
        for (Map.Entry<String, List<RuleItem>> m : ruleMap.entrySet()) {
            itemMap = Maps.newConcurrentMap();
            for (RuleItem ruleItem : m.getValue()) {
                itemMap.put(ruleItem.getId(), ruleItem.getName());
            }
            map.put(m.getKey(), itemMap);
        }
        // 打包zip
        String zipPath = createZip(list, knowledgeAuditPack, map);
        // 更新修改次数
        updateDownloadNum(knowledgeAuditPack);
        return zipPath;
    }

    private List<ReleasedKnowledgeField> getList(KnowledgeAuditPack knowledgeAuditPack) {
        List<ReleasedKnowledgeField> list = releasedKnowledgeFieldService.getBaseMapper().selectByKnowledgeAuditPack(knowledgeAuditPack);

        if (CollectionUtils.isNotEmpty(list)) {
            Set<String> tagSet = list.stream().map(ReleasedKnowledgeField::getKindValue).filter(t -> StringUtils.isNotBlank(t)).collect(Collectors.toSet());
            if (tagSet.size() > 0) {
                Map<String, String> tagMap = Maps.newConcurrentMap();
                List<Tag> allTag = tagService.queryTagByRootIdSet(tagSet);
                for (Tag tag : allTag) {
                    tagMap.put(tag.getId(), tag.getName());
                }
                knowledgeAuditPack.setTagMap(tagMap);
            }
            // 应用平台
            Map<String, String> platformMap = Maps.newConcurrentMap();
            List<Platform> platformList = platformService.list();
            for (Platform platform : platformList) {
                platformMap.put(platform.getId(), platform.getName());
            }
            knowledgeAuditPack.setPlatformMap(platformMap);
        }
        return list;
    }

    /**
     * 更新下载次数
     *
     * @param knowledgeAuditPack
     */
    private void updateDownloadNum(KnowledgeAuditPack knowledgeAuditPack) {
        String updateSql = "update knowledge_audit_pack set download_total = " + (knowledgeAuditPack.getDownloadTotal() + 1) + " where id = '" + knowledgeAuditPack.getId() + "'";
        knowledgeAuditPackService.getBaseMapper().executeUpdate(updateSql);
    }

    private void createExcel(List<ReleasedKnowledgeField> list, KnowledgeAuditPack knowledgeAuditPack, OutputStream outputStream, Map<String, Map<String, String>> dropDownMap) {
        ExcelDb excelDb = new ExcelDb();
        excelDb.setSheetName(knowledgeAuditPack.getName());
        excelDb.setTitle(knowledgeAuditPack.getName());
        List<String> headers = list.stream().map(ReleasedKnowledgeField::getName).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        headers.add("id");
        excelDb.setHeaders(headers.stream().toArray(String[]::new));
        Map<String, List<ReleasedKnowledgeField>> map = list.stream().collect(Collectors.groupingBy(ReleasedKnowledgeField::getKnowledgeId));
        List<ExcelDb> excelDblist = Lists.newArrayList();
        List<String[]> data = Lists.newArrayList();
        for (List<ReleasedKnowledgeField> fieldList : map.values()) {
            String[] fieldStr = new String[headers.size()];
            for (int i = 0; i < fieldStr.length - 1; i++) {
                fieldStr[i] = getFieldValue(fieldList.get(i), 1, null, knowledgeAuditPack, dropDownMap);
            }
            fieldStr[fieldStr.length - 1] = fieldList.get(0).getKnowledgeId();
            data.add(fieldStr);
        }
        excelDb.setData(data);
        excelDblist.add(excelDb);
        ExcelUtil.excelDownload(excelDblist, outputStream);
    }

    private String createZip(List<ReleasedKnowledgeField> list, KnowledgeAuditPack knowledgeAuditPack, Map<String, Map<String, String>> dropdownMap) throws Exception {
        long currentTime = System.currentTimeMillis();
        String filePath = ApplicationContextUtil.BASE_DOWN_FORDER + "/exportzip/" + currentTime + "/";
        File storeFile = new File(filePath);
        if (!storeFile.exists()) {
            storeFile.mkdirs();
        }
        org.dom4j.Document document = DocumentHelper.createDocument();// 由DocumentHelper得到一个空的Document
        document.setXMLEncoding("utf-8");// 设置xml头条的Encoding
        // addElement写入根节点 addAttribute节点属性的键和值
        org.dom4j.Element root = document.addElement("root");
        // 由根节点 可以得到下二级的节点
        org.dom4j.Element id = root.addElement(knowledgeAuditPack.getKnowledgeLibName());
        // 根据knowledgeid进行分组
        Map<String, List<ReleasedKnowledgeField>> map = list.stream().collect(Collectors.groupingBy(ReleasedKnowledgeField::getKnowledgeId));
        for (List<ReleasedKnowledgeField> fieldList : map.values()) {
            org.dom4j.Element knowledge = id.addElement("knowledge");
            LinkedHashMap<String, String> fieldMap = Maps.newLinkedHashMap();
            for (ReleasedKnowledgeField item : fieldList) {
                fieldMap.put(item.getName(), getFieldValue(item, 2, storeFile, knowledgeAuditPack, dropdownMap));
            }
            for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                org.dom4j.Element child = knowledge.addElement(entry.getKey());
                if (StringUtils.isNotBlank(entry.getValue())) {
                    child.addText("<![CDATA[" + entry.getValue() + "]]>");
                }
            }
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        /** 将document中的内容写入文件中 */
        XMLWriter writer = new XMLWriter(new FileWriter(new File(storeFile + "/" + knowledgeAuditPack.getName() + ".xml")), format);
        // 设置生成xml文件特殊字符不转义
        writer.setEscapeText(false);
        writer.write(document);
        writer.close();
        // zip打包
        ZipUtil.toZip(filePath, knowledgeAuditPack.getPassword(), knowledgeAuditPack.getName());
        return filePath;
    }

    /**
     * 取得对应字段值
     *
     * @param releasedKnowledgeField
     * @param type                   1 导处excel，不需要导出图片，不需要更改图片路径 2导出xml,需要导出图片，需要更改图片路径
     * @return
     */
    private String getFieldValue(ReleasedKnowledgeField releasedKnowledgeField, int type, File storeFile, KnowledgeAuditPack knowledgeAuditPack, Map<String, Map<String, String>> map) {
        String value = "";
        value = releasedKnowledgeField.getProperty();
        int kind = releasedKnowledgeField.getKind();
        if (1 == kind) {
            // 富文本
            value = releasedKnowledgeField.getProperty();
        } else if (2 == kind) {
            // 参照
            String tagIds = releasedKnowledgeField.getProperty();
            if (StringUtils.isNotBlank(tagIds) && !StringUtils.equals(tagIds, "[]")) {
                Map<String, String> tagMap = knowledgeAuditPack.getTagMap();
                tagIds = tagIds.replaceAll("\\[\\[", "").replaceAll("]]", "").replaceAll("\"", "").replaceAll("'", "");
                String[] splitTagIds = tagIds.replaceAll("],\\[", ";").split(";");
                List<String> resultList = Lists.newArrayList();
                for (String splitTagId : splitTagIds) {
                    String[] temp = splitTagId.split(",");
                    List<String> tagNameList = Lists.newArrayList();
                    for (String s : temp) {
                        tagNameList.add(tagMap.get(s));
                    }
                    resultList.add(StringUtils.join(tagNameList, "->"));
                }
                value = StringUtils.join(resultList, ";");
            } else {
                value = "";
            }
        } else if (3 == kind || 5 == kind) {
            if (StringUtils.isNotBlank(releasedKnowledgeField.getProperty()) && !StringUtils.equals(releasedKnowledgeField.getProperty(), "[]")) {
                // 单选或者多选下拉
                String kindValue = releasedKnowledgeField.getKindValue();
                String ruleId = releasedKnowledgeField.getProperty().replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", "").replaceAll("'", "");
                String[] tempStr = ruleId.split(",");
                List<String> list = Lists.newArrayList();
                for (String s : tempStr) {
                    list.add(map.get(kindValue).get(s));
                }
                value = StringUtils.join(list, ";");
            } else {
                value = "";
            }
        } else if (7 == kind) {
            // 多值输入框
            if (StringUtils.isBlank(releasedKnowledgeField.getProperty()) || StringUtils.equals(releasedKnowledgeField.getProperty(), "[]")) {
                value = "";
            } else {
                value = releasedKnowledgeField.getProperty().replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", "").replaceAll("'", "").replaceAll(",", ";");
            }
        } else if (8 == kind || 9 == kind) {
            // 关联本知识库/其他知识库
            if (StringUtils.isBlank(releasedKnowledgeField.getProperty()) || StringUtils.equals(releasedKnowledgeField.getProperty(), "[]")) {
                value = "";
            } else {
                JSONArray jsonArray = JSONObject.parseArray(releasedKnowledgeField.getProperty());
                List<String> list = Lists.newArrayList();
                for (Object o : jsonArray) {
                    JSONObject s = (JSONObject) o;
                    list.add(s.getString("name"));
                }
                value = StringUtils.join(list, ";");
            }
        } else if (10 == kind) {
            // 关联平台
            if (StringUtils.isBlank(releasedKnowledgeField.getProperty()) || StringUtils.equals(releasedKnowledgeField.getProperty(), "[]")) {
                value = "";
            } else {
                Map<String, String> platformMap = knowledgeAuditPack.getPlatformMap();
                String[] platForm = releasedKnowledgeField.getProperty().replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", "").replaceAll("'", "").split(",");
                List<String> platNameList = Lists.newArrayList();
                for (String s : platForm) {
                    platNameList.add(platformMap.get(s));
                }
                value = StringUtils.join(platNameList, ";");
            }
        } else if (4 == kind || 11 == kind) {
            JSONObject jsonObject = JSONObject.parseObject(value);
            String paths = jsonObject.getString("paths");
            if (StringUtils.equals(paths, "[]")) {
                return "";
            }
        } else if (12 == kind) {
            // 文件
            if (StringUtils.equals(value, "[]")) {
                return "";
            }
        }
        // 处理图片路径
        if (2 == type && StringUtils.isNotBlank(value)) {
            // 图片类型
            if (1 == kind) {
                return handleImg(handleImg(value, 0, storeFile), 1, storeFile);
            } else if (4 == kind || 11 == kind) {
                JSONObject jsonObject = JSONObject.parseObject(value);
                String paths = jsonObject.getString("paths");
                if (StringUtils.equals(paths, "[]")) {
                    return "";
                }
                String additional = jsonObject.getString("additional");
                String comment = jsonObject.getString("comment");
                String imgType = jsonObject.getString("type");
                String classification = jsonObject.getString("classification");
                String title = jsonObject.getString("title");
                String[] pathStr = paths.replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", "").split(",");
                Element pathBody = Jsoup.parse("").body();
                for (String s : pathStr) {
                    pathBody.appendElement(4 == kind ? "img" : "video").attr("src", s).attr("additional", additional)
                            .attr("comment", comment).attr("type", imgType)
                            .attr("classification", classification).attr("title", title);
                }
                return handleImg(pathBody.html(), 4 == kind ? 0 : 1, storeFile);
            } else if (12 == kind) {
                // 文件
                if (StringUtils.equals(value, "[]")) {
                    return "";
                }
                JSONArray jsonArray = JSONObject.parseArray(value);
                Element pathBody = Jsoup.parse("").body();
                for (Object o : jsonArray) {
                    JSONObject s = (JSONObject) o;
                    pathBody.appendElement("a").attr("href", s.getString("path")).text(s.getString("name"));
                }
                return handleImg(pathBody.html(), 2, storeFile);
            } else {
                return handleImg(value, 0, storeFile);
            }
        }
        return value;
    }

    /**
     * @param value
     * @param type  0 图片  1 视频  2 文件
     * @return
     */
    private String handleImg(String value, int type, File storeFile) {
        Element bodEelement = Jsoup.parse(value).body();
        Elements imgElements = null;
        // 图片
        if (0 == type) {
            imgElements = bodEelement.getElementsByTag("img");
        } else if (1 == type) {
            imgElements = bodEelement.getElementsByTag("video");
        } else {
            imgElements = bodEelement.getElementsByTag("a");
        }
        if (imgElements.size() > 0) {
            for (Element imgElement : imgElements) {
                // 下载图片
                String src = 2 == type ? imgElement.attr("href") : imgElement.attr("src");
                if (StringUtils.isBlank(src)) {
                    continue;
                }
                String imgSrc = ApplicationContextUtil.BASE_DOWN_FORDER;
                if (0 == type) {
                    imgSrc += src.replace("/ymer/action/file/showImage?filename=", "");

                } else if (1 == type) {
                    imgSrc += src.replace("/pmph/action/video/play?filename=", "");
                } else {
                    imgSrc += src.replace("/pmph/action/file/getFile?filename=", "");
                }
                String fileName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1);
                File file = new File(imgSrc);
                if (!file.exists()) {
                    return value;
                }
                copyImage(file, type, storeFile, fileName);
                if (2 == type) {
                    imgElement.attr("href", "pics/" + fileName);
                } else {
                    imgElement.attr("src", "pics/" + fileName);
                }
            }
            value = bodEelement.html();
        }
        return value;
    }

    private void copyImage(File file, int type, File storeFile, String fileName) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(file);
            // copy地址
            storeFile = new File(storeFile + "/" + "pics");
            if (!storeFile.exists()) {
                storeFile.mkdirs();
            }
            outputStream = new FileOutputStream(new File(storeFile + "/" + fileName));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            if (type == 0) {
                Image srcImg = ImageIO.read(new File(storeFile + "/" + fileName));
                if (srcImg.getWidth(null) < 200) {
                    return;
                }
                BufferedImage bufferedImage = new YmerFileCtrl().addWaterMark(srcImg);
                ImageIO.write(bufferedImage, "png", new File(storeFile + "/" + fileName));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
                if (null != outputStream) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public void saveKnowledgeSyncStatus(KnowledgeSyncStatus knowledgeSyncStatus) {
        // 先删除再新增;
        knowledgeSyncStatusService.remove(Wrappers.lambdaQuery(KnowledgeSyncStatus.class)
                .eq(KnowledgeSyncStatus::getKnowledgeId, knowledgeSyncStatus.getKnowledgeId())
                .eq(KnowledgeSyncStatus::getPlatformId, knowledgeSyncStatus.getPlatformId()));
        knowledgeSyncStatusService.save(knowledgeSyncStatus);
    }

    public List<TempKnowledge> queryTempList(String status, String updateTime, String classify, String platform, String version, String editor, String auditor, String name, String id, String drugInfoLibCompany, Integer isCompose) {
        String sql = "";
        List tempKnowledge = null;
        if (status.equals("unpublished")) {
            sql += "select * from temp_knowledge where id in(select ti.knowledge_id from task_item ti LEFT JOIN  task t on t.id=ti.task_id where ti.status='" + TaskItem.STATUS_PASS + "' and t.system_type='knowledge') and deleted=0 and  knowledge_lib_id =" + "'" + id + "'";
            sql = getTempSearch(updateTime, classify, platform, version, editor, auditor, name, sql, drugInfoLibCompany, isCompose);
            tempKnowledge = tempKnowledgeService.getBaseMapper().executeMultiSelect(sql);
        }
        return tempKnowledge;
    }


    public int TempAllRelease(String id, String name) {
        System.out.println(System.currentTimeMillis() + "开始时间-----------------------");
        saveTempAndRelease(id);
        HistoryUtils.save(id, name, History.OPERATE_RELEASE, History.OPERATE_RESULT_SUCCESS);
        System.out.println(System.currentTimeMillis() + "结束时间-----------------------");
        return 1;
    }


    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void syncWaitAndFailedKnowledgeToPlatform(String platformId, String knowledgeLibId, String username) {
        KnowledgeLib knowledgeLib = knowledgeLibService.getBaseMapper().selectById(knowledgeLibId);
        List<KnowledgeSyncStatus> knowledgeSyncStatusList = knowledgeSyncStatusService.lambdaQuery()
                .eq(KnowledgeSyncStatus::getPlatformId, platformId)
                .eq(KnowledgeSyncStatus::getKnowledgeLibId, knowledgeLibId)
                .ne(KnowledgeSyncStatus::getKind, KnowledgeSyncStatus.KIND_SUCCESS).list();
        for (KnowledgeSyncStatus knowledgeSyncStatus : knowledgeSyncStatusList) {
            ReleasedKnowledge releasedKnowledge = releasedKnowledgeService.getById(knowledgeSyncStatus.getKnowledgeId());
            if (Objects.isNull(releasedKnowledge)) {
                knowledgeSyncStatusService.removeById(knowledgeSyncStatus.getId());
            } else {
                releasedKnowledge.setKnowledgeLibName(knowledgeLib.getName());
                rocketMQProducerService.sendKnowledge(knowledgeSyncStatus.getPlatformId(), releasedKnowledge, username);
            }
        }
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void syncKnowledgesToPlatforms(String syncToPlatformType, String knowledgeLibId, List<ReleasedKnowledge> selectedKnowledges, String bindingPlatform, JSONObject searchParams, String username, String knowledgeId) {
        KnowledgeLib knowledgeLib = knowledgeLibService.getBaseMapper().selectById(knowledgeLibId);
        if (Objects.equals("selected", syncToPlatformType)) {
            for (ReleasedKnowledge releasedKnowledge : selectedKnowledges) {
                releasedKnowledge = releasedKnowledgeService.getById(releasedKnowledge.getId());
                releasedKnowledge.setKnowledgeLibName(knowledgeLib.getName());
                // 给releasedKnowledge对象设置fields
                String sql = "select * from released_knowledge_field where knowledge_id = '" + releasedKnowledge.getId() + "' order by id";
                List<KnowledgeField> releasedKnowledgeFields = Lists.newArrayList();
                releasedKnowledgeFieldService.getBaseMapper().executeMultiSelect(sql).forEach(releasedKnowledgeFields::add);
                releasedKnowledge.setKnowledgeFieldList(releasedKnowledgeFields);
                rocketMQProducerService.sendKnowledge(bindingPlatform, releasedKnowledge, username);
            }
        } else if (Objects.equals("waitAndFailed", syncToPlatformType)) {
            // 一键同步, 同步当前搜索条件下待同步和失败数据;
            // 查询当前搜索条件的知识;
            String sql = "select * from released_knowledge ";
            sql += getWherePart(searchParams.getString("name"),
                    searchParams.getString("platformId"),
                    searchParams.getString("synStatus"),
                    searchParams.getString("updateTime"),
                    bindingPlatform,
                    searchParams.getString("id"),
                    searchParams.getString("drugInfoLibCompany"),
                    searchParams.getInteger("isCompose"));
            List<ReleasedKnowledge> releasedKnowledgeArray = releasedKnowledgeService.getBaseMapper().executeMultiSelect(sql);
            // 知识数组, 赋值knowledge_lib_name, 转id -> entity 映射, 便于查找;
            releasedKnowledgeArray.stream().forEach(rk -> rk.setKnowledgeLibName(knowledgeLib.getName()));
            Map<String, ReleasedKnowledge> id2EntityMap = releasedKnowledgeArray.stream().collect(Collectors.toMap(ReleasedKnowledge::getId, rk -> rk));
            // 查询当前知识库, 当前平台, 所有待同步和同步失败的知识;
            List<KnowledgeSyncStatus> knowledgeSyncStatusList = knowledgeSyncStatusService.lambdaQuery()
                    .eq(KnowledgeSyncStatus::getPlatformId, bindingPlatform)
                    .eq(KnowledgeSyncStatus::getKnowledgeLibId, knowledgeLibId)
                    .ne(KnowledgeSyncStatus::getKind, KnowledgeSyncStatus.KIND_SUCCESS).list();
            // 遍历当前待同步和同步失败的知识, 如果在当前搜索条件下, 则同步;
            knowledgeSyncStatusList.stream()
                    .map(ksf -> id2EntityMap.get(ksf.getKnowledgeId()))
                    .filter(Objects::nonNull)
                    .forEach(rk -> rocketMQProducerService.sendKnowledge(bindingPlatform, rk, username));
        } else if (Objects.equals("all", syncToPlatformType)) {
            syncAllKnowledgeToPlatforms(knowledgeLibId, bindingPlatform, username, knowledgeLib);
        } else if (StringUtils.equals("single", syncToPlatformType)) {
            ReleasedKnowledge releasedKnowledge = releasedKnowledgeService.getById(knowledgeId);
            releasedKnowledge.setKnowledgeLibName(knowledgeLib.getName());
            // 给releasedKnowledge对象设置fields
            String sql = "select * from released_knowledge_field where knowledge_id = '" + releasedKnowledge.getId() + "' order by id";
            List<KnowledgeField> releasedKnowledgeFields = Lists.newArrayList();
            releasedKnowledgeFieldService.getBaseMapper().executeMultiSelect(sql).forEach(releasedKnowledgeFields::add);
            releasedKnowledge.setKnowledgeFieldList(releasedKnowledgeFields);
            rocketMQProducerService.sendKnowledge(bindingPlatform, releasedKnowledge, username);
        }
    }

    // 同步全量数据,
    // 数据量过大, 例如药物信息库 6w+数据量, 字段内容也比较大, 粗略估计, 一个知识库的数据可能达到GB数量级;
    // 全量查询都放到内存里, 有OOM风险, 分页查询, 分页推送;
    private void syncAllKnowledgeToPlatforms(String knowledgeLibId, String bindingPlatform, String username, KnowledgeLib knowledgeLib) {
        Integer count = releasedKnowledgeService.lambdaQuery()
                .eq(ReleasedKnowledge::getKnowledgeLibId, knowledgeLibId)
                .eq(ReleasedKnowledge::getDeleted, ReleasedKnowledge.DELETED_NO)
                .count();
        // 分页推送, 避免OOM;
        for (int i = 0; i <= count / 100; i++) {
            // 当前线程主要是往线程池添加任务, 如果当前线程池有未执行的任务, 则当前线程挂起, 等待线程池其它任务执行完毕再往线程池添加新的推送任务, 避免OOM;
            while (CollectionUtils.isNotEmpty(ExecutorServiceFactory.getInstance().getQueue())) {
                Thread.yield();
            }
            List<ReleasedKnowledge> releasedKnowledgeList = releasedKnowledgeService.lambdaQuery()
                    .eq(ReleasedKnowledge::getKnowledgeLibId, knowledgeLibId)
                    .eq(ReleasedKnowledge::getDeleted, ReleasedKnowledge.DELETED_NO)
                    .page(new Page<>(i + 1, 100)).getRecords();
            for (ReleasedKnowledge releasedKnowledge : releasedKnowledgeList) {
                releasedKnowledge.setKnowledgeLibName(knowledgeLib.getName());
                List<KnowledgeField> releasedKnowledgeFields = Lists.newArrayList();
                releasedKnowledgeFieldService.lambdaQuery().eq(ReleasedKnowledgeField::getKnowledgeId, releasedKnowledge.getId())
                        .orderByAsc(ReleasedKnowledgeField::getId).list().forEach(releasedKnowledgeFields::add);
                releasedKnowledge.setKnowledgeFieldList(releasedKnowledgeFields);
                rocketMQProducerService.sendKnowledge(bindingPlatform, releasedKnowledge, username);
            }
        }
    }

    public void multiInsertTaskItem(String taskId, String remark, String username, List<ReleasedKnowledge> releasedKnowledgeList, Set<String> knowledgeInProcessIdSet) {
        PMPHAppUtil.threadUsername.set(username);

        for (ReleasedKnowledge releasedKnowledge : releasedKnowledgeList) {
            if (!knowledgeInProcessIdSet.contains(releasedKnowledge.getId())) {
                TaskItem taskItem = new TaskItem();
                taskItem.setTaskId(taskId);
                taskItem.setKnowledgeId(releasedKnowledge.getId());
                taskItem.setName(releasedKnowledge.getName());
                taskItem.setRemark(remark);
                // 查询上次关联的子任务, 字数;
                TaskItem dbTaskItem = taskItemService.getBaseMapper().selectBeanByWherePart(
                        " knowledge_id = '" + releasedKnowledge.getId() + "' " +
                                " order by updated_time limit 1");
                if (Objects.nonNull(dbTaskItem)) {
                    taskItem.setWordsCount(dbTaskItem.getWordsCount());
                }
                taskItem.setType(TaskItem.TYPE_EDIT);
                taskService.saveTaskItem(taskItem, username);
            }
        }
    }

    public List<KnowledgeLibField> getKnowledgeLibField(String sql) {
        List<KnowledgeLibField> knowledgeLibFields = knowledgeLibFieldMapper.executeMultiSelect(sql);
        return knowledgeLibFields;
    }

    public List<ReleasedKnowledge> getReasedKnledgeList(String knowledgeLibId, String bindingPlatform, JSONObject searchParams, KnowledgeLib knowledgeLib) {
        String sql = "select * from released_knowledge ";
        sql += getWherePart(searchParams.getString("name"),
                searchParams.getString("platformId"),
                searchParams.getString("synStatus"),
                searchParams.getString("updateTime"),
                bindingPlatform,
                searchParams.getString("id"),
                searchParams.getString("drugInfoLibCompany"),
                searchParams.getInteger("isCompose"));
        List<ReleasedKnowledge> releasedKnowledgeArray = releasedKnowledgeService.getBaseMapper().executeMultiSelect(sql);
        // 知识数组, 赋值knowledge_lib_name, 转id -> entity 映射, 便于查找;
        releasedKnowledgeArray.stream().forEach(rk -> rk.setKnowledgeLibName(knowledgeLib.getName()));
        Map<String, ReleasedKnowledge> id2EntityMap = releasedKnowledgeArray.stream().collect(Collectors.toMap(ReleasedKnowledge::getId, rk -> rk));
        // 查询当前知识库, 当前平台, 所有待同步和同步失败的知识;
        List<KnowledgeSyncStatus> knowledgeSyncStatusList = knowledgeSyncStatusService.lambdaQuery()
                .eq(KnowledgeSyncStatus::getPlatformId, bindingPlatform)
                .eq(KnowledgeSyncStatus::getKnowledgeLibId, knowledgeLibId)
                .ne(KnowledgeSyncStatus::getKind, KnowledgeSyncStatus.KIND_SUCCESS).list();
        // 遍历当前待同步和同步失败的知识, 如果在当前搜索条件下, 则同步;
        List<ReleasedKnowledge> releasedKnowledges = knowledgeSyncStatusList.stream()
                .map(ksf -> id2EntityMap.get(ksf.getKnowledgeId()))
                .filter(Objects::nonNull).collect(Collectors.toList());
        return releasedKnowledges;
    }

}